package cn.gdchent.springbootsecurity.utils;

import java.io.*;

public class FileUtil {

    public static File getExistHolder(String parent, String[] holderPath) {
        for (String tempPath : holderPath) {
            File file = new File(parent, tempPath);
            if (file.exists()) {
                return file;
            }
        }
        return null;
    }

    public static void copyFile(File source, File dest) throws IOException {
        try (InputStream input = new FileInputStream(source); OutputStream output = new FileOutputStream(dest)) {
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, bytesRead);
            }
            output.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void deleteDir(String dirPath) {
        File file = new File(dirPath);
        detele(file);
    }

    public static void deleteDir(File dirPath) {
        detele(dirPath);
    }

    private static void detele(File dirPath) {
        if (dirPath.isDirectory()) {
            File[] files = dirPath.listFiles();
            if (files != null) {
                for (File value : files) {
                    deleteDir(value.getAbsolutePath());
                }
            }
        }
        if (!dirPath.delete()) {
            throw new RuntimeException("delete file failed: " + dirPath.getName());
        }
    }
}
